<!--  -->
<template>
  <div>
    <el-dialog title="绑定物资" :visible.sync="openGoodsDialog" width="90%" @close="closeGoodsDialog">
      <div class="wrapper">
        <div class="tree">
          <el-card :body-style="{ padding: '0px' }" style="max-height: 600px; overflow-y: auto;">
            <!-- ----------------------------- 选择工序树 ------------------------- -->
            <el-tree :data="ProcedureTree" @node-click="nodeClick" @check="nodeCheck" @check-change="checkChange" :default-expanded-keys="expandedKey" :props="{label:'name',  children: 'children'}" ref="processTree" show-checkbox highlight-current node-key="uuid" check-strictly :default-checked-keys="expandedKey">
              <span class="custom-tree-node" :class="checkProcess.uuid == data.uuid?'active':''" slot-scope="{node,data}">
                <span>
                  <span>{{ node.label }}</span>
                </span>
                <span>{{ node.sort }}</span>
              </span>
            </el-tree>
          </el-card>
        </div>
        <div class="goods">
          <span>工序：{{checkProcess.name}}</span>
          {{expandedKey}}
          --------------------
          {{checkProcess}}
          <el-table :data="goodsList" ref="multipleTable" @selection-change="selectChange" @select='onTableSelect'>
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="name" label="物资名称" width="100">
            </el-table-column>
            <!-- <el-table-column prop="spec" label="规格型号">
            </el-table-column>
            <el-table-column prop="dw" label="单位">
            </el-table-column>
            <el-table-column prop="materialType" label="类型">
            </el-table-column> -->
            <el-table-column prop="num" label="总数量" width="70">
            </el-table-column>
            <el-table-column prop="undisNum" label="可分配数" width="90">
            </el-table-column>
            <el-table-column label="分配数量">
              <template slot-scope="scope">
                <span>
                  <el-input-number :class="scope.row.undisNum <0 || scope.row.fillNum>scope.row.num ?'el-input-number-error':''" v-model="scope.row.fillNum" size="mini" controls-position="right" @change="handleChange(scope)" :min="0" :disabled="JSON.stringify(checkProcess) == '{}'">
                  </el-input-number>
                  <div class="errorText" v-if="scope.row.undisNum <0 ||scope.row.fillNum>scope.row.num">分配数量错误,请重新分配</div>
                </span>
              </template>
            </el-table-column>
          </el-table>
          <!-- {{checkProcessList}} -->
          -------------------------
          <div v-for="item in checkProcessList" :key="item.uuid">
            {{item.name}}
            <span v-for="b in item.bindmaterial" :key="b.materialUuid">
              {{b.name}}-{{b.fillNum}}
            </span>
          </div>

          -------------------------
          <div v-for="item in computedGoods" :key="item.uniqueName">
            <span>
              {{item.gxname}}-{{item.wzname}}--{{item.fillNum}}
            </span>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeGoodsDialog">取 消</el-button>
        <el-button @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  props: {
    openGoodsDialog: {
      type: Boolean
    },
    bindGoods: { type: Array },
    templateUuid: { type: String }
  },
  data () {
    return {
      postProdedMaters: [],
      expandedKey: [],
      ProcedureTree: [],
      goodsList: [],
      checkProcess: {}, //当前点击的工序
      checkProcessList: [], //当前点击的工序
      computedGoods: [],
      sumGoodsList: []
    };
  },


  watch: {
    // bindGoods (val) {
    //   this.sumGoods(val)
    //   if (val.length > 0) {
    //     this.checkProcess = val[0]
    //   }
    //   this.computedGoods = val.filter(item => item.uniqueName !== '')

    // },
    openGoodsDialog (val) {
      if (val) {
        this.expandedKey = []
        this.getSelectedGoods(this.templateUuid)
        this.sumGoods(this.bindGoods)
        if (this.bindGoods.length > 0) {
          this.checkProcess = this.bindGoods[0]
        }
        this.computedGoods = this.bindGoods.filter(item => item.uniqueName !== '')
        this.computedGoods.forEach(ele => {
          this.expandedKey.push(ele.uuid)
        })
      }
    },
    checkProcessList: {
      handler (val) {
        console.log('绑定的工序', val)
      },
      deep: true
    },
    computedGoods (val) {
      console.log('构建物资计数器', val)

      // 计算已分配总数
      this.sumGoods(val)
      this.goodsList.forEach(item => {
        item.fillNum = 0
        val.forEach(v => {
          if (this.checkProcess.uuid + item.materialUuid == v.uniqueName) {
            item.fillNum = v.fillNum
          }
        })
      })


      // 构建返回给父组件数组
      this.checkProcessList.forEach(m => {
        m.bindmaterial = []
        val.forEach(n => {
          if (m.uuid == n.gxuuid) {
            m.bindmaterial.push(n)
            m.bindmaterial = this.uniqeByKeys(m.bindmaterial, ['materialUuid', 'fillNum'])
          }
        })
      })
    },
    checkProcess (data) {
      this.$refs.multipleTable.clearSelection();
      this.goodsList.forEach(item => {
        item.fillNum = 0
        this.computedGoods.forEach(v => {
          if (this.checkProcess.uuid + item.materialUuid == v.uniqueName) {
            item.fillNum = v.fillNum
            this.$refs.multipleTable.toggleRowSelection(item, true)
          }
        })
      })
    },
    sumGoodsList (val) {
      console.log('sumGoodsList变化', val)
      // this.goodsList.forEach(item => {
      //   if (val.length > 0) {
      //     val.forEach(v => {
      //       if (item.materialUuid == v.materialUuid) {
      //         item.undisNum = item.num - v.fillNum
      //       } else {
      //         item.undisNum = item.num
      //       }
      //     })
      //   } else {
      //     item.undisNum = item.num
      //   }
      // })

      for (let i = 0; i < this.goodsList.length; i++) {
        this.goodsList[i].undisNum = this.goodsList[i].num
        if (val.length > 0) {
          for (let j = 0; j < val.length; j++) {
            if (this.goodsList[i].materialUuid == val[j].materialUuid) {
              this.goodsList[i].undisNum = this.goodsList[i].num - val[j].fillNum
            }
          }
        }
      }
    },
  },
  created () {
    this.getProcedureTree()
  },
  mounted: {},

  methods: {
    closeGoodsDialog () {
      this.$emit('closeGoodsDialog')
    },
    getProcedureTree () {
      this.axios.get('/MKL/template/queryProcedureTree', {
        params: {
          projectUuid: '06b987ba-5263-4fb3-81a1-b51217e81201'
        }
      })
        .then(res => {
          // console.log("res+获取工序树", res);
          let treedata = res.data;
          treedata.forEach(ele => {
            let parentId = ele.parentUuid;
            if (ele.lv == 3) {
              ele.taskType = "DWGC";
            }
            if (ele.lv == 4) {
              ele.taskType = "ZDWGC";
            }
            if (ele.lv == 5) {
              ele.taskType = "FBGC";
            }
            if (ele.lv == 6) {
              ele.taskType = "ZFBGC";
            }
            if (ele.lv == 7) {
              ele.taskType = "FXGC";
            }
            if (ele.lv == 8) {
              ele.taskType = "JYP";
            }
            if (ele.lv == 9) {
              ele.taskType = "GX";
              ele.disabled = false;
              ele.isCheck = false;
              ele.bindmaterial = [];
            } else {
              ele.disabled = true;
            }
            // 是根元素的hua ,不做任何操作,如果是正常的for-i循环,可以直接continue.
            if (parentId) {
              // 如果ele是子元素的话 ,把ele扔到他的父亲的child数组中.
              treedata.forEach(d => {
                if (d.uuid === parentId) {
                  let childArray = d.children;
                  if (!childArray) {
                    childArray = [];
                  }
                  childArray.push(ele);
                  d.children = childArray;
                }
              });
            }
          });
          // 去除重复元素
          this.postProdedMaters = treedata.filter(ele => ele.lv == 9);
          this.ProcedureTree = treedata.filter(ele => ele.parentUuid == "");
          console.log("this.ProcedureTree :", this.ProcedureTree);
        });
    },
    getSelectedGoods (val) {
      this.axios.get('/MKL/templateMaterial/queryMaterialByTemplateNoPage', {
        params: {
          templateUuid: val
        }
      })
        .then((res) => {
          console.log('1111111111', res)
          res.data.forEach(e => {
            e.dw = e.auxiliaryUnitList[0]
          })
          res.data.forEach(item => {
            item.undisNum = 0
            item.fillNum = 0
          })
          this.goodsList = res.data
          this.goodsList.forEach(a => {
            this.sumGoodsList.forEach(b => {
              if (a.materialUuid === b.materialUuid) {
                a.undisNum = a.num - b.fillNum
              }
            })
          })

          this.goodsList.forEach((aa, idx) => {
            this.computedGoods.forEach(bb => {
              if (this.checkProcess.uuid + aa.materialUuid == bb.uniqueName) {
                aa.fillNum = bb.fillNum
                setTimeout(() => {
                  this.$refs.multipleTable.toggleRowSelection(this.goodsList[idx])
                }, 100)
              }
            })
          })

        })
    },
    nodeClick (data, node) {
      console.log('11', data, node)
      if (data.taskType == 'GX') {
        this.checkProcess = data
        this.expandedKey.push(data.uuid)
        this.checkProcessList.push(data)
        this.expandedKey = Array.from(new Set(this.expandedKey))
        this.checkProcessList = this.uniqeByKeys(this.checkProcessList, ['uuid']);
        // this.changeUndisNum(this.computedGoods)
        this.sumGoods(this.computedGoods)

        this.goodsList.forEach(item => {
          item.fillNum = 0
          this.computedGoods.forEach(v => {
            if (this.checkProcess.uuid + item.materialUuid == v.uniqueName) {
              item.fillNum = v.fillNum
            }
          })
        })
      }
    },
    nodeCheck (data, node) {
      console.log('33333333333', data, node)
      if (data.taskType == 'GX') {
        this.checkProcess = data;
      }

      if (node.checkedKeys.length == 0) {
        this.checkProcess = {}
      }

      let keys = node.checkedKeys
      let flag = keys.some(item => item === data.uuid);
      if (flag) {
        console.log('选择')
      } else {
        console.log('取消')
        let index = this.computedGoods.filter(item => item.gxuuid == data.uuid)
        if (index.length > 0) {
          this.$confirm("该工序下绑定的物资将清空，确定解绑?", "提示", {
            cancelButtonText: "取消",
            confirmButtonText: "确定",
            type: "warning"
          }).then(() => {
            this.computedGoods = this.computedGoods.filter(item => item.gxuuid !== data.uuid)
            this.$refs.multipleTable.clearSelection();
            this.checkProcess = {}
          }).catch(() => {
            this.$refs.processTree.setCheckedKeys([data.uuid].concat(keys));
          })
        }
      }
    },
    checkChange (data, check) {
      console.log('node,data,key', data, check)
      if (data.taskType == 'GX') {
        if (check) {
          this.expandedKey.push(data.uuid)
          this.checkProcessList.push(data)
          this.expandedKey = Array.from(new Set(this.expandedKey))
          this.checkProcessList = this.uniqeByKeys(this.checkProcessList, ['uuid']);
        } else {
          this.expandedKey.splice(this.expandedKey.findIndex(item => item === data.uuid), 1)
          this.checkProcessList.splice(this.checkProcessList.findIndex(item => item.uuid === data.uuid), 1)
        }
      }
    },
    handleChange (scope) {
      let row = scope.row
      if (JSON.stringify(this.checkProcess) == '{}') {
        console.log('4444444444444', scope.$index)
        this.$message.error('请选择工序');
        return false
      } else {
        console.log('计数器', row)
        if (parseInt(row.fillNum) >= 0) {
          this.$refs.multipleTable.toggleRowSelection(this.goodsList[scope.$index], true)
          // 构建物资计数器
          if (this.computedGoods.length > 0) {
            this.computedGoods.forEach(c => {
              if (this.checkProcess.uuid + row.materialUuid == c.uniqueName) {
                c.fillNum = row.fillNum
              } else {
                this.computedGoods.push({
                  gxuuid: this.checkProcess.uuid,
                  gxname: this.checkProcess.name,
                  taskType: this.checkProcess.taskType,
                  procedureType: this.checkProcess.procedureType,
                  wzname: row.name,
                  code: row.code,
                  spec: row.spec,
                  wzunit: row.dw,
                  materialType: row.materialType,
                  fillNum: row.fillNum,
                  materialUuid: row.materialUuid,
                  uniqueName: this.checkProcess.uuid + row.materialUuid
                })
              }
            })
          } else {
            this.computedGoods.push({
              gxuuid: this.checkProcess.uuid,
              gxname: this.checkProcess.name,
              taskType: this.checkProcess.taskType,
              procedureType: this.checkProcess.procedureType,
              wzname: row.name,
              code: row.code,
              spec: row.spec,
              wzunit: row.dw,
              materialType: row.materialType,
              fillNum: row.fillNum,
              materialUuid: row.materialUuid,
              uniqueName: this.checkProcess.uuid + row.materialUuid
            })
          }
          this.computedGoods = this.uniqeByKeys(this.computedGoods, ['uniqueName', 'fillNum']);

          if (parseInt(row.fillNum) == 0) {
            this.computedGoods.forEach((cc, index) => {
              if (this.checkProcess.uuid + row.materialUuid == cc.uniqueName) {
                this.computedGoods.splice(index, 1)
              }
            })
            this.computedGoods = this.uniqeByKeys(this.computedGoods, ['uniqueName', 'fillNum']);
            this.$refs.multipleTable.toggleRowSelection(this.goodsList[scope.$index], false)
          }
        }
      }

    },
    selectChange (selection) {
      console.log('选项变化', selection)
    },
    onTableSelect (rows, row) {
      let selected = rows.length && rows.indexOf(row) !== -1
      console.log(selected, row)  // true就是选中，0或者false是取消选中
      if (!selected) {
        for (let i = 0; i < this.computedGoods.length; i++) {
          if (this.computedGoods[i].uniqueName == this.checkProcess.uuid + row.materialUuid) {
            this.computedGoods.splice(i, 1)
          }
        }
      }
    },
    submit () {
      for (let i = 0; i < this.goodsList.length; i++) {
        if (this.goodsList[i].undisNum < 0) {
          this.$message.error('已分配数量不得超过可分配数量，请重新分配！')
          return false
        }
        if (this.goodsList[i].fillNum > this.goodsList[i].num) {
          this.$message.error('分配数量不得大于总数量！')
          return false
        }
      }

      let list = []
      this.checkProcessList.forEach(item => {
        if (item.bindmaterial.length > 0) {
          item.bindmaterial.forEach(ee => {
            list.push(ee)
          })
        } else {
          list.push({
            gxuuid: item.uuid,
            gxname: item.name,
            taskType: item.taskType,
            procedureType: item.procedureType,
            wzname: '',
            code: '',
            spec: '',
            wzunit: '',
            materialType: '',
            fillNum: 0,
            materialUuid: '',
            uniqueName: ''
          })
        }
      })

      console.log('提交的数据', list)
      this.$emit('checkedProcessGoods', list)
      this.closeGoodsDialog()
    },

    // 已分配数求和
    sumGoods (arr) {
      let obj2 = arr.reduce((resp, obj) => {
        var originObj = resp.find(item => item.materialUuid === obj.materialUuid);
        if (originObj) {
          originObj.fillNum += obj.fillNum;
        } else {
          resp.push({
            wzname: obj.wzname,
            materialUuid: obj.materialUuid,
            fillNum: obj.fillNum
          })
        }
        return resp;
      }, [])
      console.log('计算已分配总数', obj2)
      this.sumGoodsList = obj2
    },
    obj2key (obj, keys) {
      var n = keys.length,
        key = [];
      while (n--) {
        key.push(obj[keys[n]]);
      }
      return key.join('|');
    },
    uniqeByKeys (array, keys) {
      var arr = [];
      var hash = {};
      for (var i = 0, j = array.length; i < j; i++) {
        var k = this.obj2key(array[i], keys);
        if (!(k in hash)) {
          hash[k] = true;
          arr.push(array[i]);
        }
      }
      return arr;
    }


  }
}
</script>
<style lang='stylus' scoped>
.wrapper {
  display flex
  flex-direction row
  .tree {
    width 300px
  }
  .goods {
    flex 1
  }
  .el-input-number-error {
    border 1px solid red !important
    border-radius 5px
  }
  .errorText {
    color red
  }
}
</style>